import store from '../store/index';
import configs from '../service/config';

const util = {
  /**
   * 生成随机字符串
   */
  getRandomNum(length) {
    if (typeof length !== 'number') length = 20;
    const chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
    let result = '';
    while (result.length < length) {
      const index = Math.floor(Math.random() * (chars.length));
      result += chars[index];
    }
    const hasIncludes = store.state.randomList.includes(result);
    if (hasIncludes) {
      return util.getRandomNum(length);
    }
    store.commit('updateRandomList', result);
    return result;
  },
  /**
   * 校正时间格式
   */
  timeFormat(value) {
    return value < 10 ? '0' + value : String(value);
  },
  /**
   * 对用户账号进行显示加密（屏蔽）处理
   * 手机号 前三位 + **** + 后四位
   * 邮箱号 前三位 + **** + @
   */
  encryptUsername(value) {
    return value.includes('@')
      ? value.replace(/(\w{3})\w+(@)/, "$1****$2")
      : value.replace(/^(\d{3})\d+(\d{4})$/, "$1****$2");
  },
  /**
   * 从url读取最基本的路径
   */
  getBasicPathFromUrl() {
    const hashPath = window.location.hash.split('?')[0];
    return (hashPath && hashPath.includes('/')) ? hashPath.split('/')[1] : '';
  },
  /**
   * 从url读取参数
   */
  getQueryFromUrl() {
    const hashQuery = window.location.hash.split('?')[1];
    const query = {};
    if (hashQuery) {
      const queries = hashQuery.split('&');
      queries.forEach(queryItem => {
        if (queryItem && queryItem.includes('=')) {
          const queryItemArr = queryItem.split('=');
          query[queryItemArr[0]] = queryItemArr[1];
        }
      });
    }
    return query;
  },
  /**
   * 字符串首字母大写
   */
  firstUpperCase(value) {
    if (typeof value !== 'string') return;
    return `${value.slice(0, 1).toUpperCase()}${value.slice(1)}`;
  },
  /**
   * 判断类型
   */
  checkType(data) {
    return Object.prototype.toString.call(data).slice(8, -1).toLowerCase();
  },

  /**
   * 存cookie的方法
   */
  setCookie(name, value, day = 2) {
    const exp = new Date();
    exp.setTime(exp.getTime() + day * 24 * 60 * 60 * 1000);
    document.cookie = `${name}=${value};expires=${exp.toGMTString()};path=/;`;
  },

  /**
   * 取cookie的方法
   */
  getCookie(cname) {
    const name = cname + '=';
    const ca = document.cookie.split(';');
    for (let i = 0; i < ca.length; i++) {
      const c = ca[i].trim();
      if (c.indexOf(name) === 0) return c.substring(name.length, c.length);
    }
    return '';
  },

  /**
   * 删除cookie的方法
   */
  deleteCookie(name) {
    const exp = new Date();
    exp.setTime(exp.getTime() + -1 * 24 * 60 * 60 * 1000);
    document.cookie = `${name}=;expires=${exp.toGMTString()};path=/;`;
  },

  /**
   * 设置rem
   * @param value 设置的大小
   * @param hasUnit 是否设置px单位
   */
  setRem(value, hasUnit = true) {
    // const baseSize = 192;
    // 页面的设计稿宽度
    // const designWidth = 1920;
    const htmlDom = document.getElementsByTagName('html')[0];
    const htmlWidth = document.documentElement.clientWidth || document.body.clientWidth;
    const htmlHeight = document.documentElement.clientHeight || document.body.clientHeight;
    // 当前页面宽度相对于 1920 宽的缩放比例
    // const scale = htmlWidth / designWidth;
    // 设置根元素字体大小
    // let size = baseSize * Math.min(scale, 2);
    let size = htmlWidth / 10;
    if (htmlWidth > 1800 && htmlWidth < 1920 && htmlHeight < 980 && htmlHeight > 820) {
      size = 185;
    }
    if (value) {
      const val = String(value).replace(/px/g, '');
      const currentSize = val * (parseFloat(size) / 192);
      return hasUnit ? `${currentSize}px` : currentSize;
    }
    htmlDom.style.fontSize = `${size}px`;
  },

  /**
   * 获取本地存储
   * @param key {String}
   */
  getLocalStorage(key) {
    try {
      const data = key ? localStorage.getItem(key) : '';
      return data ? JSON.parse(data) : '';
    } catch (e) {
      // eslint-disable-next-line
      console.info('getLocalStorage Error', e);
    }
  },

  /**
   * 设置本地存储
   * @param option {Object | String}
   * @param value {any}
   */
  setLocalStorage(option, value) {
    try {
      const type = util.checkType(option);
      if (type === 'string' && value) {
        localStorage.setItem(option, JSON.stringify(value));
        return;
      }
      if (type !== 'object') return;
      Object.keys(option).forEach(key => {
        localStorage.setItem(key, option[key]);
      });
    } catch (e) {
      // eslint-disable-next-line
      console.info('setLocalStorage Error', e);
    }
  },

  /**
   * 删除本地存储
   * @param keys {String | Array} 键值
   */
  deleteLocalStorage(keys) {
    const type = util.checkType(keys);
    if (type === 'string') {
      localStorage.removeItem(keys);
      return;
    }
    if (type === 'array') {
      keys.forEach(item => {
        localStorage.removeItem(item);
      });
    }
  },

  /**
   * Uint8Array转base64
   * @param u8Arr Uint8Array格式的文件数据
   */
  arrayBufferToBase64(u8Arr) {
    // const length = u8Arr.byteLength;
    // const table = ['A','B','C','D','E','F','G','H',
    //   'I','J','K','L','M','N','O','P',
    //   'Q','R','S','T','U','V','W','X',
    //   'Y','Z','a','b','c','d','e','f',
    //   'g','h','i','j','k','l','m','n',
    //   'o','p','q','r','s','t','u','v',
    //   'w','x','y','z','0','1','2','3',
    //   '4','5','6','7','8','9','+','/'];
    // let base64Str = '';
    // let i;
    // for(i = 0; length - i >= 3; i += 3) {
    //   const num1 = u8Arr[i];
    //   const num2 = u8Arr[i + 1];
    //   const num3 = u8Arr[i + 2];
    //   base64Str += table[num1 >>> 2] +
    //     table[((num1 & 0b11) << 4) | (num2 >>> 4)] +
    //     table[((num2 & 0b1111) << 2) | (num3 >>> 6)] +
    //     table[num3 & 0b111111];
    // }
    // const lastByte = length - i;
    // if(lastByte === 1) {
    //   const lastNum1 = u8Arr[i];
    //   base64Str += table[lastNum1 >>> 2] + table[((lastNum1 & 0b11) << 4)] + '==';
    // } else if(lastByte === 2) {
    //   const lastNum1 = u8Arr[i];
    //   const lastNum2 = u8Arr[i + 1];
    //   base64Str += table[lastNum1 >>> 2] +
    //     table[((lastNum1 & 0b11) << 4) | (lastNum2 >>> 4)] +
    //     table[(lastNum2 & 0b1111) << 2] +
    //     '=';
    // }
    // return base64Str;

    const CHUNK_SIZE = 0x8000;
    let index = 0;
    const len = u8Arr.length;
    let result = '';
    let slice;
    while (index < len) {
      slice = u8Arr.subarray(index, Math.min(index + CHUNK_SIZE, len));
      result += String.fromCharCode.apply(null, slice);
      index += CHUNK_SIZE;
    }
    return btoa(result);
  },
  /**
   * 校验文件或图片地址
   * @param url {String}
   */
  checkUrl(url) {
    if (!url) return '';
    return /^http(s?)/.test(url)
      ? url : configs.upload + url.replace(/^\/{1}/, '');
  },
  /**
   * 预览文件
   * @param {String} url
   * @param {Boolean} hasOpen
   */
  previewUrl(url, hasOpen = true) {
    if (!url) return '';
    const urlList = url.split(',');
    let fileUrl = '';
    for (const i in urlList) {
      fileUrl += `${util.checkUrl(i)}|`;
    }
    try {
      fileUrl = encodeURIComponent(window.btoa(fileUrl));
    } catch (e) {}
    const baseUrl = `${configs.previewUrl}?url${urlList.length > 1 ? 's' : ''}=${fileUrl}`;
    hasOpen && window.open(baseUrl);
    return baseUrl;
  },
  /**
   * 根据URL下载文件
   * @param urlStr {String}
   * @param name 文件重命名
   */
  fileToUpload(urlStr, name) {
    if (!urlStr) return;
    const suffixList = urlStr.match(/(\.jpg)|(\.jpeg)|(\.png)$/);
    // 图片文件后缀
    const suffixStr = suffixList && suffixList[0];
    if (suffixStr) {
      const image = new Image();
      const reg = new RegExp(`([^\/])+${suffixStr}$`, 'g');
      const names = urlStr.match(reg) || [];
      const defaultName = names[0] ? names[0].replace(suffixStr, '') : 'image';
      // 解决跨域 Canvas 污染问题
      image.setAttribute('crossOrigin', 'anonymous');
      image.onload = () => {
        const canvas = document.createElement('canvas');
        canvas.width = image.width;
        canvas.height = image.height;
        const context = canvas.getContext('2d');
        context.drawImage(image, 0, 0, image.width, image.height);
        // 得到图片的base64编码数据
        const url = canvas.toDataURL(`image/${suffixStr.replace('.', '')}`);
        // 生成一个a元素
        const a = document.createElement('a');
        // 创建一个单击事件
        const event = new MouseEvent('click');
        // 设置图片名称
        a.download = name || defaultName;
        // 将生成的URL设置为a.href属性
        a.href = url;
        // 触发a的单击事件
        a.dispatchEvent(event);
      };
      image.src = urlStr;
      return;
    }
    const fileList = urlStr.split(',');
    fileList.forEach(url => window.open(util.checkUrl(url)));
  },
  // 将base64文件转为file
  convertBase64UrlToBlob(base64Str) {
    try {
      // 需去掉url的头，并转换为byte
      const bytes = window.atob(base64Str);
      // 处理异常,将ascii码小于0的转换为大于0
      const ab = new ArrayBuffer(bytes.length);
      const ia = new Uint8Array(ab);
      for(let i = 0; i < bytes.length; i++) {
        ia[i] = bytes.charCodeAt(i);
      }
      const fileData = new Blob([ab], { type: 'image/png' });
      new File(
        [fileData],
        `${new Date().getTime()}.png`,
        { type: 'image/png' }
      );
    } catch (e) {}
  },
};

export default util;
